-- lua_script.lua

local cjson_safe = require("cjson.safe")  -- 可选，仅用于调试打印

-- 1. 从 Nginx 环境中提取关键字段
local remote_addr = ngx.var.remote_addr or "-"
local remote_user = ngx.var.remote_user or "-"
local time_local = ngx.var.time_local or ngx.localtime()
local request = ngx.var.request or ""
if request == "" then
    request = (ngx.var.request_method or "GET") .. " " .. (ngx.var.request_uri or "/") .. " " .. (ngx.var.server_protocol or "HTTP/1.1")
end
local status = ngx.var.status or "200"
local body_bytes_sent = ngx.var.body_bytes_sent or "0"
local http_referer = ngx.var.http_referer or "-"
local http_user_agent = ngx.var.http_user_agent or "-"

-- 2. 构造一行标准的 nginx access log 格式字符串
local log_line = string.format('%s - %s [%s] "%s" %s %s "%s" "%s"',
    remote_addr,
    remote_user,
    time_local,
    request,
    status,
    body_bytes_sent,
    http_referer,
    http_user_agent
)

-- 3. Unix Socket 路径
local socket_path = "/www/logai/nginx_model.sock"

-- 4. 使用 OpenResty 的 socket API 建立 Unix Socket 连接
local sock = ngx.socket.tcp()
local ok, err = sock:connect("unix:" .. socket_path)

if not ok then
    ngx.log(ngx.ERR, "连接Unix Socket失败: ", err)
    -- 连接失败时默认放行，避免影响正常流量
    return
end

-- 5. 发送日志行字符串
local bytes, err = sock:send(log_line .. "\n")
if not bytes then
    ngx.log(ngx.ERR, "发送数据失败: ", err)
    sock:close()
    return
end

-- 6. 设置接收超时（可选，建议设置）
sock:settimeout(1000)  -- 1秒超时

-- 7. 接收 Python 返回的浮点数字符串
local response, err = sock:receive("*l")
sock:close()

if not response then
    ngx.log(ngx.ERR, "未收到模型返回值: ", err)
    response = "0.00"
end

-- 8. 转为 float
local score = tonumber(response) or 0.0
ngx.log(ngx.INFO, "[MODEL] 返回的分数: ", score)

-- 9. 判断是否拦截
if score >= 0.5 then
    ngx.header["Content-Type"] = "text/html; charset=utf-8"
    
    -- 直接输出自定义HTML页面内容
    ngx.say([[
    <!DOCTYPE html>
    <html lang="zh-CN">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>访问被拒绝 - 403</title>
        <style>
            body {
                font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
                background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
                min-height: 100vh;
                display: flex;
                align-items: center;
                justify-content: center;
                margin: 0;
                padding: 20px;
            }
            .container {
                background: rgba(255, 255, 255, 0.95);
                backdrop-filter: blur(10px);
                border-radius: 20px;
                padding: 50px 40px;
                text-align: center;
                box-shadow: 0 20px 40px rgba(0, 0, 0, 0.1);
                max-width: 1000px;
                width: 100%;
                border: 1px solid rgba(255, 255, 255, 0.2);
            }
            .icon {
                font-size: 4rem;
                margin-bottom: 20px;
            }
            h1 {
                color: #2c3e50;
                font-size: 2rem;
                margin-bottom: 15px;
            }
            p {
                color: #7f8c8d;
                font-size: 1.1rem;
                line-height: 1.6;
                margin-bottom: 30px;
            }
            .code {
                background: #f8f9fa;
                color: #e74c3c;
                padding: 10px 15px;
                border-radius: 8px;
                font-family: 'Courier New', monospace;
                font-size: 1.2rem;
                font-weight: bold;
                display: inline-block;
                margin-bottom: 20px;
            }
        </style>
    </head>
    <body>
        <div class="container">
            <div class="icon">🚫</div>
            <h1>访问被拒绝</h1>
            <div class="code">403</div>
            <p>抱歉，您的请求被我们的安全AI WAF系统拦截。</p>
            <p>检测到可能的恶意行为，为了保护网站安全，我们拒绝了此次访问。</p>
        </div>
    </body>
    </html>
    ]])
    
    -- 确保不输出其他内容
    ngx.eof()
    return
end